package com.wwwarehouse.common.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.activity.media.SelectImageActivity;
import com.wwwarehouse.common.eventbus_event.ScanResultEvent;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tripartite_widget.zxing.CameraManager;
import com.wwwarehouse.common.tripartite_widget.zxing.CaptureActivityHandler;
import com.wwwarehouse.common.tripartite_widget.zxing.InactivityTimer;
import com.wwwarehouse.common.tripartite_widget.zxing.ScanningImageTools;
import com.wwwarehouse.common.tripartite_widget.zxing.ViewfinderView;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;

import de.greenrobot.event.EventBus;

/**
 * @ClassName: CaptureActivity
 * @Description: 二维码扫描
 * @author juns
 * @date 2013-8-14
 */
public class CaptureActivity extends BaseActivity implements Callback {

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private boolean playBeep;
	private boolean vibrate;
	Handler mHandler = null;

	private TextView mTitle;
	private ImageView mGoHome;

	ImageView lightBt = null; // 闪光灯按钮
	ImageView selectImgBt = null; // 选择图片按钮

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_code_scan);
		mHandler = new Handler();
		initView();
	}

	private void initView() {
		CameraManager.init(getApplication());
		initControl();
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finishActivity();
		}
		return super.onKeyDown(keyCode, event);
	}

	boolean isOpen = true;
	private void initControl() {
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		mTitle = (TextView) findViewById(R.id.common_title_msg);
		mTitle.setText("扫一扫");
		mGoHome = (ImageView) findViewById(R.id.img_back);
		mGoHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finishActivity();
			}
		});

		lightBt = (ImageView) findViewById(R.id.light_bt);
		selectImgBt = (ImageView) findViewById(R.id.select_img);

		lightBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isOpen){
					isOpen = !isOpen;

					try {
						CameraManager.get().openLight();
					} catch (RuntimeException e) {

					}
				}else{
					isOpen = !isOpen;

					try {
						CameraManager.get().offLight();
					} catch (RuntimeException e) {

					}
				}
			}
		});

		selectImgBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Intent intent = new Intent();
//				intent.setType("image/*");
//    			/* 使用Intent.ACTION_GET_CONTENT这个Action */
//				intent.setAction(Intent.ACTION_GET_CONTENT);
//   				/* 取得相片后返回本画面 */
//				startActivityForResult(intent, 1);

				Intent intent = new Intent(CaptureActivity.this, SelectImageActivity.class);
				startActivityForResult(intent, 1);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == 1) {
			String path = data.getExtras().getString(SelectImageActivity.KEY_SELECT_IMAGE_PATH);

//			Result result = scanningImage(path);
//			if (result != null) {
//				ToastUtils.showToast(result.getText());
//			}
//			else {
//				ToastUtils.showToast("未扫描到");
//			}

			ScanningImageTools.scanningImage(path, new ScanningImageTools.IZCodeCallBack() {

				@Override
				public void ZCodeCallBackUi(Result result) {
					// TODO Auto-generated method stub
					if (result == null) {
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								ToastUtils.showToast("未识别到二维码");
							}
						});
					} else {
						// 数据返回进行仿乱码处理
						final String recode = ScanningImageTools.recode(result.toString());
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								EventBus.getDefault().post(new ScanResultEvent(recode));
								finishActivity();
							}
						});
					}

				}
			});
		}
	}

	// 识别图片上的二维码的另一种方式
	protected Result scanningImage(String path) {
		if (TextUtils.isEmpty(path)) {
			return null;
		}
		// DecodeHintType 和EncodeHintType
		Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
		hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 设置二维码内容的编码
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; // 先获取原大小
		Bitmap scanBitmap = BitmapFactory.decodeFile(path, options);
		options.inJustDecodeBounds = false; // 获取新的大小

		int sampleSize = (int) (options.outHeight / (float) 200);

		if (sampleSize <= 0)
			sampleSize = 1;
		options.inSampleSize = sampleSize;
		scanBitmap = BitmapFactory.decodeFile(path, options);


		com.wwwarehouse.common.tripartite_widget.zxing.RGBLuminanceSource source = new com.wwwarehouse.common.tripartite_widget.zxing.RGBLuminanceSource(scanBitmap);
		BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
		QRCodeReader reader = new QRCodeReader();
		try {
			return reader.decode(bitmap1, hints);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
//		initBeepSound();
		vibrate = true;
	}

	@Override
	public void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	public void onDestroy() {
		if (inactivityTimer != null) {
			inactivityTimer.shutdown();
		}

//		CameraManager.get().stopPreview();
		CameraManager.get().destroy();
		super.onDestroy();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(CaptureActivity.this, decodeFormats, characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
//		Intent it = new Intent();
//		it.putExtra("RESULT", result.getText());
//		setResult(RESULT_OK, it);
//		finish();

		EventBus.getDefault().post(new ScanResultEvent(result.getText()));
		finishActivity();
	}
}
